package faw.car.ccenter.utils;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolUtils {
    /**
     * 线程池核心线程数
     */
    private static final int CORE_POOL_SIZE = 4;
    /**
     * 线程池最大线程数
     */
    private static final int MAX_POOL_SIZE = 10;
    /**
     * 额外线程空状态生存时间
     */
    private static final int KEEP_ALIVE_TIME = 10_000;
    /**
     * 阻塞队列。当核心线程都被占用，且阻塞队列已满的情况下，才会开启额外线程
     */
    private final BlockingQueue<Runnable> mWorkQueue = new ArrayBlockingQueue<Runnable>(10);
    /**
     * 线程池
     */
    private ThreadPoolExecutor mThreadPool;
    private boolean mIsWorking = false;
    private static ThreadPoolUtils mInstance;
    public static ThreadPoolUtils getInstance() {
        if (null == mInstance) {
            synchronized (ThreadPoolUtils.class){
                if(null == mInstance){
                    mInstance = new ThreadPoolUtils();
                }
            }
        }
        return mInstance;
    }
    public void init() {
        initPoolThread();
        mIsWorking = true;
    }
    private void initPoolThread() {
        mThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, mWorkQueue, threadFactory);
    }
    private final ThreadFactory threadFactory = new ThreadFactory() {
        private final AtomicInteger integer = new AtomicInteger();
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "QisiThreadPool thread:" + integer.getAndIncrement());
        }
    };
    public void execute(Runnable runnable) {
        mThreadPool.execute(runnable);
    }
    public void execute(FutureTask futureTask) {
        mThreadPool.execute(futureTask);
    }
    public void cancel(FutureTask futureTask) {
        futureTask.cancel(true);
    }
    /**
     * 销毁线程池
     */
    public void destroy() {
        if(mIsWorking){
            mIsWorking = false;
            mThreadPool.shutdown();
        }
    }
}